<template>
  <div class="login-page">
    <div class="login-container">
      <div class="login-title">
        <h1>人格魅力餐厅</h1>
      </div>
      <el-card class="login-card">
        <template #header>
          <div class="card-header">
            <h2>用户登录</h2>
          </div>
        </template>
        <el-form :model="loginForm" :rules="rules" ref="loginFormRef" label-width="80px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="loginForm.username" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              v-model="loginForm.password"
              :type="passwordVisible ? 'text' : 'password'"
              placeholder="请输入密码"
              show-password
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleLogin" :loading="loading">登录</el-button>
            <el-button @click="$router.push('/register')">注册</el-button>
            <el-button type="text" @click="$router.push('/merchant/login')">商家入口</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import axios from 'axios'

const router = useRouter()
const loginFormRef = ref<FormInstance>()
const loading = ref(false)
const passwordVisible = ref(false)

// 从localStorage获取上次登录的用户名
const savedUsername = localStorage.getItem('lastUserUsername') || ''

const loginForm = reactive({
  username: savedUsername,
  password: ''
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

// 创建axios实例
const request = axios.create({
  baseURL: 'http://localhost:8080',
  timeout: 10000
})

// 响应拦截器
request.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code !== 1) {
      return Promise.reject(new Error(res.msg || '请求失败'))
    }
    return res
  },
  error => {
    return Promise.reject(error)
  }
)

const handleLogin = async () => {
  if (!loginFormRef.value) return

  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        // 直接使用axios调用登录接口
        const res = await request({
          url: '/user/login',
          method: 'post',
          data: {
            username: loginForm.username,
            password: loginForm.password
          }
        })

        // 登录成功，存储用户信息和token
        localStorage.setItem('user', JSON.stringify(res.data))
        localStorage.setItem('token', res.data.token)

        // 保存用户名，但不保存密码
        localStorage.setItem('lastUserUsername', loginForm.username)

        ElMessage.success('登录成功')
        router.push('/user/dish')
      } catch (error: any) {
        ElMessage.error(error.message || '登录失败，请检查用户名和密码')
      } finally {
        loading.value = false
      }
    }
  })
}
</script>

<style scoped>
.login-page {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-image: url('/login-background.png');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.login-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  max-width: 800px;
}

.login-title {
  margin-bottom: 30px;
  text-align: center;
}

.login-title h1 {
  font-size: 36px;
  color: #000;
  margin: 0;
  text-shadow: 2px 2px 4px rgba(255, 255, 255, 0.5);
  font-weight: bold;
}

.login-card {
  width: 400px;
  background-color: rgba(255, 255, 255, 0.9);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  border-radius: 8px;
}

.card-header {
  text-align: center;
}
</style>
